package cn.wowjoy.office.applystock;

import android.arch.lifecycle.Observer;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.shizhefei.view.indicator.IndicatorViewPager;
import com.shizhefei.view.indicator.slidebar.ColorBar;
import com.shizhefei.view.indicator.transition.OnTransitionTextListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import cn.bingoogolapple.badgeview.BGABadgeTextView;
import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseActivity;
import cn.wowjoy.office.baselivedata.appbase.NewBaseFragment;
import cn.wowjoy.office.common.adapter.TabIndicatorBadgetAdapter;
import cn.wowjoy.office.common.widget.CommonDialog;
import cn.wowjoy.office.common.widget.CreateDialog;
import cn.wowjoy.office.common.widget.MDialog;
import cn.wowjoy.office.data.constant.Constants;
import cn.wowjoy.office.data.event.CountEvent;
import cn.wowjoy.office.data.event.StorageCodeEvent;
import cn.wowjoy.office.data.mock.PopuModel;
import cn.wowjoy.office.data.remote.ResultException;
import cn.wowjoy.office.databinding.ActivityApplyStockBinding;

@Route(path = "/applystock/applystocklist")
public class ApplyStockActivity extends NewBaseActivity<ActivityApplyStockBinding,ApplyStockViewModel> implements View.OnClickListener {

    @Autowired
    int type;

    private List<String> titles;
    private List<NewBaseFragment> fragments;
    private IndicatorViewPager indicatorViewPager;
    private TabIndicatorBadgetAdapter tabIndicatorBadgetAdapter;
    private StayOutStockFragment stayOutStockFragment;
    private CompletedFragment completedFragment;
    private MDialog waitDialog;
    private CommonDialog warningDialog;
    private String status_stay;
    private String status_completed;


    private void clearDialog(){
        if (waitDialog != null ){
            waitDialog.dismiss();
            waitDialog = null;
        }
    }

    @Override
    protected Class<ApplyStockViewModel> getViewModel() {
        return ApplyStockViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_apply_stock;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        ARouter.getInstance().inject(this);
        binding.setViewModel(viewModel);
//        viewModel.getStorageUserId();
        binding.back.setOnClickListener(this);
        binding.search.setOnClickListener(this);
        initData();
        initObserver();
        binding.tabIndicator.setScrollBar(new ColorBar(getApplicationContext(), getResources().getColor(R.color.view_line1), 4));//设置滚动条的颜色，及高度
        binding.tabIndicator.setOnTransitionListener(new OnTransitionTextListener().setColor(ContextCompat.getColor(this, R.color.appText14), ContextCompat.getColor(this, R.color.appText10)));
        indicatorViewPager = new IndicatorViewPager(binding.tabIndicator, binding.vp);
        tabIndicatorBadgetAdapter = new TabIndicatorBadgetAdapter(getSupportFragmentManager());
        tabIndicatorBadgetAdapter.setData(titles, fragments);
        indicatorViewPager.setAdapter(tabIndicatorBadgetAdapter);
        binding.vp.setCanScroll(true);
        binding.vp.setOffscreenPageLimit(2);
        viewModel.getStorageUserId();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if(EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CountEvent event) {
        if (event.getCount() <= 0){
            ((BGABadgeTextView)binding.tabIndicator.getItemView(0)).hiddenBadge();
        } else if (event.getCount() <= 99){
            ((BGABadgeTextView)binding.tabIndicator.getItemView(0)).showTextBadge(String.valueOf(event.getCount()));
        } else {
            ((BGABadgeTextView)binding.tabIndicator.getItemView(0)).showTextBadge("99");
        }
    }

    private void initDialog(){
        warningDialog = new CommonDialog.Builder()
                .showTitle(false)
                .setContent("获取权限失败，请确认是否有权限！")
                .showCancel(false)
                .setConfirmBtn("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ApplyStockActivity.this.finish();
                    }
                })
                .create();
        warningDialog.setCancelable(false);
        warningDialog.show(getSupportFragmentManager(),"");
    }
    private void initObserver(){
        viewModel.permisson.observe(this, new Observer<LiveDataWrapper<List<PopuModel>>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<List<PopuModel>> listLiveDataWrapper) {
                switch (listLiveDataWrapper.status){
                    case LOADING:
                        waitDialog = CreateDialog.waitingDialog(ApplyStockActivity.this);
                        break;
                    case SUCCESS:
                        clearDialog();
                        EventBus.getDefault().post(new StorageCodeEvent(listLiveDataWrapper.data.get(0).getStorageCode()));
                        stayOutStockFragment.setStorageCode(listLiveDataWrapper.data.get(0).getStorageCode());
                        completedFragment.setStorageCode(listLiveDataWrapper.data.get(0).getStorageCode());
                        break;
                    case ERROR:
                        clearDialog();
                        if (listLiveDataWrapper.error instanceof ResultException){
                            initDialog();
                        } else {
                            handleException(listLiveDataWrapper.error,false);
                        }
                        break;
                }
            }
        });
    }

    private void initData() {
        initStatus();
        titles = new ArrayList<>();
        titles.add("待出库");
        titles.add("已完成");
        fragments = new ArrayList<>();
        stayOutStockFragment = StayOutStockFragment.newInstance(status_stay, type);
        completedFragment = CompletedFragment.newInstance(status_completed, type);
        fragments.add(stayOutStockFragment);
        fragments.add(completedFragment);
    }


    private void initStatus(){
        switch (type){
            case Constants.RECEIPTS_CODE_APPLY:
                status_stay = "8-3";
                status_completed = "8-5";
                binding.title.setText("申领出库");
                break;
            case Constants.RECEIPTS_CODE_APPLY_FOR:
                binding.title.setText("申请出库");
                break;
            case Constants.RECEIPTS_CODE_ALLOT:
                status_stay = "38-8";
                status_completed = null;
                binding.title.setText("调拨出库");
                break;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.back:
                onBackPressed();
                break;
            case R.id.search:
                break;
        }
    }
}
